#ifndef ICEBEARLEDWIDGET_H
#define ICEBEARLEDWIDGET_H
#include <QtMqtt/QtMqtt>
#include <QtMqtt/QMqttClient>
#include <QWidget>
#include "config.h"
#include "fsmpEvents.h"
#include "fsmpProximity.h"
#include "fsmpSevensegLed.h"
#include "keyboard.h"
#include "ui_icebearledwidget.h"
#define PRESSED_MSG "the %d key is pressed"
#define RELEASE_MSG "the %d key is release"
QT_BEGIN_NAMESPACE
namespace Ui {
class IceBearLedWidget;
}


class IceBearLedWidget : public QWidget
{
    Q_OBJECT

public:
    IceBearLedWidget(QWidget *parent = 0);
    ~IceBearLedWidget();

private:
    Ui::IceBearLedWidget *ui;
    QTimer *timer;
    fsmpEvents *myEvent;
    fsmpProximity *infrared;
    fsmpSevensegLed *sled;
    bool isPeople=false;
    int timeCount=0;
    KeyBoard *keyboard;
    void onlineService(){
        //绑定信号与槽，当收到消息后调用槽函数
        if(client != nullptr)
        {
            qDebug()<< "Is Connected";
        }
        else
        {
            qDebug()<< "Error unConnected";
        }
    }
    void localService(){
        connect(myEvent,&fsmpEvents::peopleDetected,this,&IceBearLedWidget::InfraredChange);
        connect(myEvent,&fsmpEvents::keyPressed,this,&IceBearLedWidget::keyDown);
        connect(myEvent,&fsmpEvents::keyRelessed,this,&IceBearLedWidget::keyUp);
        timer = new QTimer(this);
        connect(timer,SIGNAL(timeout()),this,SLOT(getInfrared()));
        timer->start(10);
    }

    void InfraredChange(bool flag){
        if (flag)
        {
            publishMsg(true,0);
            ui->isPeplLabel->setText("people is near");
            isPeople=true;
        }else
        {
            publishMsg(false,0);
            ui->isPeplLabel->setText("no people");
            isPeople=false;
        }
    }

    void keyDown(int key){
        ui->keyLabel->setText(QString::asprintf(PRESSED_MSG,key));
    }
    void keyUp(int key){
        ui->keyLabel->setText(QString::asprintf(RELEASE_MSG,key));
    }
    void connectSuccess()
    {
        qDebug() << "connect sucess";
    }

    void connectError()
    {
        qDebug() << "connect error";
    }
    void publishMsg(bool flag ,int id){
        QString msg = QString::asprintf(INFRARED,flag ? "true" : "false",id);
        client->publish(QString(MQTT_DEVICE_SIM),msg.toLatin1().data());
    }

private slots:

    void getInfrared()
    {
        if(isPeople)
        {

            ui->distanceLabel->setText(QString::number(infrared->getValue()));
        }else
        {
            ui->distanceLabel->setText(0);
        }

    }
    void on_ledButton_clicked();
    void on_backButton_clicked();
};

QT_END_NAMESPACE
#endif // ICEBEARLEDWIDGET_H
